package com.hatricks.is.asm;

import jodd.io.FileUtil;
import lombok.SneakyThrows;

import java.io.File;

@SuppressWarnings("CallToPrintStackTrace")
public class HelloWorldRunner {
    @SneakyThrows
    public static void main(String[] args) {
        byte[] classData = HelloWorldGenerator.generateHelloWorldClass();

        File file = FileUtil.file("D:\\work_space\\java_work_space\\public_utils\\src\\main\\java\\com\\hatricks\\asm\\a.class");
        FileUtil.writeBytes(file, classData);

        CustomClassLoader loader = new CustomClassLoader();
        Class<?> helloWorldClass = loader.defineClass("HelloWorld", classData);
        try {
            // Invoke the main method
            helloWorldClass.getMethod("main", String[].class).invoke(null, (Object) args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Custom class loader to define a class from byte array
    static class CustomClassLoader extends ClassLoader {
        public Class<?> defineClass(String name, byte[] b) {
            return defineClass(name, b, 0, b.length);
        }
    }
}
